﻿using MyWeb.Business.Base;
using MyWeb.Model;
using MyWeb.Model.Models;
using MyWeb.Repository.UnitOfWorks;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyWeb.Business.System.Impl
{
    public class RoleService:BaseBusiness<Role>,IRoleService
    {
        private readonly SqlSugarScope _dbBase;
        public RoleService(IUnitOfWorkManage unitOfWorkManage)
        {
            _dbBase = unitOfWorkManage.GetDbClient();
        }

        public async Task<List<Role>> GetPage(RefAsync<int> count,int page = 1,int pageSize = 50, string key = "")
        {
            var roles = await _dbBase.Queryable<Role>()
                .Where(r => r.IsDeleted == false && (key == "" || r.Name.Contains(key)))
                .ToPageListAsync(page, pageSize,count);
            return roles;
        }
        public async Task<bool> Edit(Role role)
        {

            await _dbBase.BeginTranAsync();
            try
            {
                var r = await _dbBase.Queryable<Role>().Where(r => r.Id == role.Id && r.IsDeleted == false).SingleAsync();
                if(r is null)
                {
                    throw new Exception("角色不存在！");
                }
                r.Name = role.Name;
                r.Description = role.Description;
                r.OrderSort = role.OrderSort;
                r.Dids = role.Dids;
                r.AuthorityScope = role.AuthorityScope;
                r.Enabled = role.Enabled;
                r.ModifyTime = DateTime.Now;

                await _dbBase.Updateable(r).ExecuteCommandAsync();
                await _dbBase.CommitTranAsync();
            }
            catch{
                await _dbBase.RollbackTranAsync();
                throw;
            }
            return true;
        }
        public async Task<bool> Remove(long id)
        {
            await _dbBase.BeginTranAsync();
            try
            {
                var r = await _dbBase.Queryable<Role>().Where(r => r.Id == id && r.IsDeleted == false).SingleAsync();
                if (r is null)
                {
                    throw new Exception("角色不存在！");
                }
                r.IsDeleted = true;

                await _dbBase.Updateable(r).ExecuteCommandAsync();
                await _dbBase.CommitTranAsync();
            }
            catch
            {
                await _dbBase.RollbackTranAsync();
                throw;
            }
            return true;
        }
    }
}
